package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.util.JsonResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/permission")
public class PermissionController {
    @Autowired
    private IPermissionService permissionService;

    //提供一个方法处理查询所有部门的请求,响应HTML
    @RequestMapping("/list")
    //要贴上注解,因为页面要取值的话不贴@ModelAttribute去到的值是${queryObject.xxx},首字符会小写
    public String list(Model model, @ModelAttribute("qo") QueryObject qo) {//创建qo对象
        //这里不再是调用listAll的方法,而是我嗯创建的query方法
        // List<Permission> permissions = permissionService.listAll();
        PageInfo result = permissionService.query(qo);//这里没有qo对象需要我们在上面创建,返回的方法是pageResult
        model.addAttribute("result", result);
        return "permission/list";// /WEB-INF/views/permission/potentialList.ftl
    }

    @RequestMapping("/input")
    public String input(Long id, Model model) {
        //判断id是否为空
        if (id != null) {
            Permission permission = permissionService.get(id);
            model.addAttribute("permission", permission);
        }
        return "permission/input";// /WEB-INF/views/permission/input.ftl
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Permission permission) {
        if (permission.getId() == null) {
            permissionService.save(permission);
        } else {
            permissionService.update(permission);
        }
        //重定向跳转到list页面
        return "redirect:/permission/list.do";//http://localhost/permission/list.do
    }

    @RequestMapping("/delete")
    public String delete(Long id) {
        //判断是否为空
        if (id != null) {
            permissionService.delete(id);
        }
        //重定向,// http://localhost/permission/list.do
        return "redirect:/permission/list.do";
    }

    @RequestMapping("/reload")
    @ResponseBody//把返回的对象那个转换为json格式的数据响应给前段,前段发送ajax请求
    public JsonResult reload() {
        try {
            permissionService.reload();
            return new JsonResult(true,"加载成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"加载失败");
        }
    }
}

